import { get_api_name } from "#utils/rollup_utils"
import type { Config } from '#types/unicloud'
import esbuild from 'esbuild';
import write from 'write'
import { TSBufferProtoGenerator } from 'tsbuffer-proto-generator';
import { isExists } from "./fsV"
import { resolve } from 'path';
import * as fs from 'fs'
import log from "#utils/log"
import { replace } from "esbuild-plugin-replace";
import { getProto, getApiJson } from './utils'
import { clearFormat } from "../src/utils/pubFunction"
import { readFileSync } from 'fs'
export async function presetApi(path: string) {
    const api = `
import type { Api } from "unicloud-pack"
import { ReqData } from "./proto"
export const main: Api<ReqData> = {
    enable: true,  
    // 开启校验
    validate:true,
    handler: async (event, context) => {

    }
}
`
    await crartApiDir(`${path}/index.ts`, api)
    const proto = `
export type ReqData = {
     
}
`
    await crartApiDir(`${path}/proto.ts`, proto)
}

export function crartApiDir(path: string, buffer: string) {
    return new Promise((resolve, reject) => {
        write(path, buffer, (err) => {
            if (err) {
                reject(err);
            } else {
                resolve(null);
            }
        });
    });
}

export function devBuildApi(entryPoints: Record<string, string>, common: string[] = []) {
    log.info("[shim:unicloud]开始编译API文件")
    return new Promise<void>((resolve, reject) => {
        const buildParams: Record<string, unknown> = {
            entryPoints: entryPoints,
            allowOverwrite: true, // 是否覆盖
            banner: {
                js: '',
            },
            plugins: [],
            format: 'cjs',
            platform: 'node', //编译node平台
            bundle: true, //是否启用捆绑
            outdir: `${process.env.UNICLOUDURL}/module`,
            absWorkingDir: process.cwd(), //构建的工作目录
            minify: false, // 压缩代码
            splitting: false, // 提取公共函数
            inject: [] //导入另一个文件替换全局变量
        }
        if (common.length > 0) {
            //替换全局公共函数
            buildParams.plugins = [replace({
                "global.common": "require"
            })]
            buildParams.external = common
        }
        esbuild
            .build(buildParams)
            .then(() => {
                resolve()
                log.success("编译API文件成功")
            })
            .catch(() => {
                reject()
                log.err("编译API文件失败")
            });
    })
}

export function devBuildRouter(inputUrl: string, common: string[] = []) {
    log.info("开始编译路由文件")
    return new Promise<void>((resolve, reject) => {
        const buildParams: Record<string, unknown> = {
            entryPoints: [inputUrl],
            allowOverwrite: true, // 是否覆盖
            banner: {
                js: '',
            },
            format: 'cjs',
            platform: 'node', //编译node平台
            bundle: true, //是否启用捆绑
            outdir: `${process.env.UNICLOUDURL}`,
            absWorkingDir: process.cwd(), //构建的工作目录
            minify: false, // 压缩代码
            splitting: false, // 提取公共函数
            inject: [] //导入另一个文件替换全局变量
        }
        if (common.length > 0) {
            //替换全局公共函数
            buildParams.plugins = [replace({
                "global.common": "require"
            })]
            buildParams.external = common
        }
        esbuild
            .build(buildParams)
            .then(() => {
                resolve()
                log.success("编译路由文件成功")
            })
            .catch(() => {
                reject()
                log.err("编译路由文件失败")
            });
    })

}

// 生成json参数文件
export async function writeDevGenerator(apiName: string, protoUrl: string) {
    const generator = new TSBufferProtoGenerator({
        keepComment: false
    });
    log.info("[shim:unicloud]开始生成校验文件")
    const protoList = await generator.generate([protoUrl])
    const dev_schema_url = resolve(process.cwd(), process.env.UNICLOUDURL + "/schema/TSBuffer.json")
    let TSBuffer_Json: Record<string, any> = {}
    if (isExists(dev_schema_url) === 'file') {
        let schema = fs.readFileSync(dev_schema_url, 'utf8');
        TSBuffer_Json = JSON.parse(schema)
    }
    const api = apiName.replaceAll(".", "/")
    TSBuffer_Json[apiName] = protoList[`${process.env.APIINPUT}/${api}/proto/ReqData`]
    write.sync(dev_schema_url, JSON.stringify(TSBuffer_Json));
}

/* 
* 生成json参数文件 新
* protoUrl proto.ts 文件path
*/
export async function writeDevValidate(protoUrl: string) {
    if (isExists(protoUrl) === 'file') {
        const apiurl = protoUrl.replace("proto.ts", 'index.ts')
        const content = clearFormat(readFileSync(apiurl, 'utf8'));
        if (content.length === 0) return;
        // 格式化后的API对象数据
        const ApiModule = getApiJson(content)
        if (!ApiModule.validate) return;
        const generator = new TSBufferProtoGenerator({
            keepComment: false
        });
        log.info("[shim:unicloud]开始生成校验文件")
        const protoList = await generator.generate([protoUrl])
        const dev_schema_url = resolve(process.cwd(), process.env.UNICLOUDURL + "/schema/TSBuffer.json")
        let TSBuffer_Json: Record<string, any> = {}
        if (isExists(dev_schema_url) === 'file') {
            let schema = fs.readFileSync(dev_schema_url, 'utf8');
            TSBuffer_Json = JSON.parse(schema)
        }
        const apiName = get_api_name(protoUrl, 'proto.ts')
        const api = apiName.replaceAll(".", "/")
        TSBuffer_Json[api] = getProto(protoList[`${process.env.APIINPUT}/${api}/proto/ReqData`])
        write.sync(dev_schema_url, JSON.stringify(TSBuffer_Json));
    }
}
// 生成临时路由文件
export function unicloud_index(config: Config) {
    const index_url = resolve(process.cwd(), 'dev/index.js').split(`${process.env.SPLITSTR}`).join("/")
    const uni_index = `
    const path = require('path');
    const Router = require(path.resolve(process.cwd(), "${index_url}"))
    exports.main = (event, content) => {
        return Router.main(event, content)
    };`
    write.sync(process.env.UNICLOUDURL + '/index.js', uni_index);
}